import { Action } from "../Action/Action";
import { BehaviourNode } from "../BehaviorNode";
import { BehaviorTree } from "../BehaviorTree";
import { RunStatus } from "../IBehaviourTree";
/**
action = root.findNextAction(input);
if action is not empty then
action.Execute(request,  input)  //request是输出的请求
else
print “no action is available”
 */
/**
 * 串行节点
 */

export class Sequence extends BehaviourNode {
    children: BehaviourNode[] = []
    status: RunStatus = RunStatus.Completed;
    runIdx: number = 0;
    /**离开节点 */
    leave(): boolean {
        return true
    }
    /**返回执行子节点 */
    async Tick(): Promise<any> {
        this.runIdx = 0;
        /**检查子节点 */
        let isOk = false;
        let status: RunStatus;
        // 全部节点都返回Completed才返回Completed,失败一个就返回Failure,runIdx重置
        // 返回Running就返回Running,并且run
        if (BehaviorTree.debug) {
            console.log('分支---', this.nodeName, status)
        }
        do {
            status = await this.children[this.runIdx].Tick();
            if ((status == RunStatus.Completed && this.runIdx >= this.children.length - 1)
                || status == RunStatus.Running
                || status == RunStatus.Failure
            ) {
                isOk = true
            }
            this.runIdx++;
        } while (!isOk)

        this.status = status;
        return status;
    }

    addNode(node: BehaviourNode): Sequence {
        this.children.push(node);
        return this;
    }
    removeNode(node: BehaviourNode): Sequence {
        if (this.children.includes(node)) {
            this.children.splice(this.children.indexOf(node), 1);
        }
        return this;
    }
    HasNode(node: BehaviourNode): boolean {
        return this.children.includes(node);
    }
}